package offer;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreDemo {
    public static void main(String[] args) {
        // 模拟3个资源
        Semaphore semaphore = new Semaphore(3);

        // 模拟6个线程，但是只有3个线程可以拿到资源
        for (int i = 0; i < 6; i++) {
            new Thread(() -> {
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "\t 获取到资源");
                    Random random = new Random();
                    int waitSecond = random.nextInt(3);
                    TimeUnit.SECONDS.sleep(waitSecond);
                    System.out.println(Thread.currentThread().getName() + "\t" + waitSecond + "秒后释放资源");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    // semaphore释放当前资源
                    semaphore.release();
                }
            }, String.valueOf(i)).start();
        }
    }
}
